package com.zhj.juc.demo15;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @PackageName:com.zhj.juc.demo15
 * @ClassName:Test2Spinlock
 * @auter: 朱慧杰
 * @date:2020/7/25 0025 19:38
 **/
public class Test2Spinlock {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    // 加锁
    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "==> MY Lock!");

        // 自旋锁
        while (!atomicReference.compareAndSet(null,thread)) {

        }
    }

    // 解锁
    public void myUnLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "==> MY UnLock!");

        atomicReference.compareAndSet(thread,null);
    }

}

class Test {

    public static void main(String[] args) {

        Test2Spinlock spinlock = new Test2Spinlock();

        new Thread(()->{
            spinlock.myLock();
            try {
                System.out.println("休息一下");
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                spinlock.myUnLock();
            }
        },"T1").start();

        new Thread(()->{
            spinlock.myLock();
            try {
                System.out.println(Thread.currentThread().getName() + "休息一下");
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                spinlock.myUnLock();
            }
        },"T2").start();

    }
}
